package org.light.verb;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.light.core.Verb;
import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.Dropdown;
import org.light.domain.Field;
import org.light.domain.JavascriptBlock;
import org.light.domain.JavascriptMethod;
import org.light.domain.Method;
import org.light.domain.Signature;
import org.light.domain.Statement;
import org.light.domain.Type;
import org.light.easyui.EasyUIPositions;
import org.light.exception.ValidateException;
import org.light.generator.NamedStatementListGenerator;
import org.light.oracle.generator.MybatisOracleSqlReflector;
import org.light.utils.MybatisSqlReflector;
import org.light.utils.PgsqlReflector;
import org.light.utils.StringUtil;
import org.light.utils.WriteableUtil;

public class ListAll extends Verb implements EasyUIPositions {
	protected Set<Field> deniedFields = new TreeSet<>();
	@Override
	public Method generateDaoImplMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName("ListAll" + StringUtil.capFirst(this.domain.getPlural()));
			method.setNoContainer(false);
			method.addSignature(new Signature(1, "db","*sql.DB"));
			method.setReturnType(new Type("[] "+this.domain.getDomainSuffix()+"."+this.domain.getType()));
							
			List<Writeable> sList = new ArrayList<Writeable>();
			
			if (StringUtil.isBlank(this.getDbType())||this.getDbType().equalsIgnoreCase("MariaDB")||this.getDbType().equalsIgnoreCase("MySQL")) {
				sList.add(new Statement(1000L,1,"sql := \""+MybatisSqlReflector.generateSelectAllStatementWithDeniedFields(domain,deniedFields)+"\""));
			}else if (this.getDbType().equalsIgnoreCase("PostgreSQL")||this.getDbType().equalsIgnoreCase("pgsql")) {
				sList.add(new Statement(1000L,1,"sql := \""+PgsqlReflector.generateSelectAllStatementWithDeniedFields(domain,deniedFields)+"\""));
			}else if (this.getDbType().equalsIgnoreCase("Oracle")) {
				sList.add(new Statement(1000L,1,"sql := \""+MybatisOracleSqlReflector.generateSelectAllStatementWithDeniedFields(domain,deniedFields)+"\""));
			}
			
			sList.add(new Statement(2000L,1,"stmt, err := db.Prepare(sql)"));
			sList.add(new Statement(2500L,1,"defer stmt.Close()"));
			sList.add(new Statement(3000L,1,"if err != nil {"));
			sList.add(new Statement(4000L,2,"panic(err)"));
			sList.add(new Statement(5000L,1,"}"));
			sList.add(new Statement(6000L,1,"rows, err := stmt.Query()"));
			sList.add(new Statement(7000L,1,"if err != nil {"));
			sList.add(new Statement(8000L,2,"panic(err)"));
			sList.add(new Statement(9000L,1,"}"));
			sList.add(new Statement(10000L,1,"var "+this.domain.getLowerFirstPlural()+" [] "+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix()+""));
			sList.add(new Statement(11000L,0,""));
			sList.add(new Statement(12000L,1,"for rows.Next() {"));
			
			StringBuilder sb = new StringBuilder();
			if (this.domain.getDomainId()!=null) sList.add(new Statement(13000L,2,"var "+this.domain.getDomainId().getLowerFirstFieldName()+" "+ this.domain.getDomainId().getFieldTypeWithParseImage()));
			if (this.domain.getDomainName()!=null) sList.add(new Statement(14000L,2,"var "+this.domain.getDomainName().getLowerFirstFieldName()+" "+ this.domain.getDomainName().getFieldTypeWithParseImage()));
			if (this.domain.getActive()!=null) {
				if ("oracle".equalsIgnoreCase(this.getDbType()))  sList.add(new Statement(15000L,2,"var "+this.domain.getActive().getLowerFirstFieldName()+" int"));
				else  sList.add(new Statement(15000L,2,"var "+this.domain.getActive().getLowerFirstFieldName()+" "+ this.domain.getActive().getFieldTypeWithParseImage()));
			}
			long serial = 16000L;
			
			if (this.domain.getDomainId()!=null) sb.append("&").append(this.domain.getDomainId().getLowerFirstFieldName()).append(",");
			if (this.domain.getDomainName()!=null) sb.append("&").append(this.domain.getDomainName().getLowerFirstFieldName()).append(",");
			if (this.domain.getActive()!=null) sb.append("&").append(this.domain.getActive().getLowerFirstFieldName()).append(",");
			for (Field f:this.domain.getPlainFields()) {
				if (!this.deniedFields.contains(f)) {
					if ((f instanceof Dropdown || "int64".equals(f.getFieldType()))&& "oracle".equalsIgnoreCase(this.domain.getDbType())){
						sList.add(new Statement(serial,2,"var "+f.getLowerFirstFieldName()+" NullString"));
						sb.append("&").append(f.getLowerFirstFieldName()).append(",");
						serial += 1000L;
						continue;
					}
					if ("oracle".equalsIgnoreCase(this.getDbType())&&"bool".equals(f.getFieldType())) {
						sList.add(new Statement(serial,2,"var "+f.getLowerFirstFieldName()+" int"));
						sb.append("&").append(f.getLowerFirstFieldName()).append(",");
						serial += 1000L;
					}else {
						sList.add(new Statement(serial,2,"var "+f.getLowerFirstFieldName()+" "+ f.getFieldNullTypeWithParseImage()));
						sb.append("&").append(f.getLowerFirstFieldName()).append(",");
						serial += 1000L;
					}
				}
			}
			String fieldsQuery = sb.toString();
			if (fieldsQuery.endsWith(",")) fieldsQuery = fieldsQuery.substring(0,fieldsQuery.length()-1);

			sList.add(new Statement(serial,0,""));
			sList.add(new Statement(serial+1000L,2,"err := rows.Scan("+fieldsQuery+")"));
			sList.add(new Statement(serial+2000L,2,"if err != nil {"));
			sList.add(new Statement(serial+3000L,3,"panic(err)"));
			sList.add(new Statement(serial+4000L,2,"}"));
			sList.add(new Statement(serial+5000L,2,"var "+this.domain.getLowerFirstDomainName()+" "+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix()+""));
			
			if (this.domain.getDomainId()!=null) sList.add(new Statement(serial+6000L,2,""+this.domain.getLowerFirstDomainName()+".Set"+this.domain.getDomainId().getCapFirstFieldName()+"("+this.domain.getDomainId().getLowerFirstFieldName()+")"));
			if (this.domain.getDomainName()!=null) sList.add(new Statement(serial+7000L,2,""+this.domain.getLowerFirstDomainName()+".Set"+this.domain.getDomainName().getCapFirstFieldName()+"("+this.domain.getDomainName().getLowerFirstFieldName()+")"));
			if (this.domain.getActive()!=null) {
				if ("oracle".equalsIgnoreCase(this.getDbType())) sList.add(new Statement(serial+8000L,2,""+this.domain.getLowerFirstDomainName()+".Set"+this.domain.getActive().getCapFirstFieldName()+"(utils.ParseInttoBool("+this.domain.getActive().getLowerFirstFieldName()+"))"));
				else sList.add(new Statement(serial+8000L,2,""+this.domain.getLowerFirstDomainName()+".Set"+this.domain.getActive().getCapFirstFieldName()+"("+this.domain.getActive().getLowerFirstFieldName()+")"));
			}
			serial += 9000L;
			for (Field f:this.domain.getPlainFields()) {
				if (!this.deniedFields.contains(f)) {
					if ((f instanceof Dropdown || "int64".equals(f.getFieldType()))&& "oracle".equalsIgnoreCase(this.domain.getDbType())){
						sList.add(new Statement(serial,2,""+this.domain.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(utils.ParseNullStringtoInt64("+f.getLowerFirstFieldName()+"))"));
						serial += 1000L;
						continue;
					}
					switch (f.getFieldType()) {
					case "bool": 
						if ("oracle".equalsIgnoreCase(this.domain.getDbType())) sList.add(new Statement(serial,2,""+this.domain.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(utils.ParseInttoBool("+f.getLowerFirstFieldName()+"))"));
						else sList.add(new Statement(serial,2,""+this.domain.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(utils.ParseNullBool("+f.getLowerFirstFieldName()+"))"));
						break;
					case "string": 
						sList.add(new Statement(serial,2,""+this.domain.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(utils.ParseNullString("+f.getLowerFirstFieldName()+"))"));
						break;
					case "int64": 
						sList.add(new Statement(serial,2,""+this.domain.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(utils.ParseNullInt64("+f.getLowerFirstFieldName()+"))"));
						break;
					case "float64": 
						sList.add(new Statement(serial,2,""+this.domain.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(utils.ParseNullFloat64("+f.getLowerFirstFieldName()+"))"));
						break;
					case "int32": 
						sList.add(new Statement(serial,2,""+this.domain.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(utils.ParseNullInt32("+f.getLowerFirstFieldName()+"))"));
						break;
					default:
						sList.add(new Statement(serial,2,""+this.domain.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"("+f.getLowerFirstFieldName()+")"));
					}
					serial += 1000L;
				}
			}
			sList.add(new Statement(serial,2,""+this.domain.getLowerFirstPlural()+" = append("+this.domain.getLowerFirstPlural()+", "+this.domain.getLowerFirstDomainName()+")"));
			sList.add(new Statement(serial+1000L,1,"}"));
			sList.add(new Statement(serial+2000L,1,"return "+this.domain.getLowerFirstPlural()+""));
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}
	@Override
	public Method generateDaoMethodDefinition() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName("ListAll" + StringUtil.capFirst(this.domain.getPlural()));
			method.addSignature(new Signature(1, "db","*sql.DB"));
			method.setReturnType(new Type("[] "+this.domain.getDomainSuffix()+"."+this.domain.getType()));
			return method;
		}
	}
	@Override
	public Method generateServiceMethodDefinition() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName("ListAll" + StringUtil.capFirst(this.domain.getPlural()));
			method.setReturnType(new Type("[] "+this.domain.getDomainSuffix()+"."+this.domain.getType()));
			return method;
		}
	}
	@Override
	public Method generateServiceImplMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName("ListAll" + StringUtil.capFirst(this.domain.getPlural()));
			method.setReturnType(new Type("[] "+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix()));
			Method daomethod = this.generateDaoMethodDefinition();
			List<Writeable> list = new ArrayList<Writeable>();
			list.add(new Statement(1000L,1,"db := database.DB"));
			list.add(NamedStatementListGenerator.generateServiceImplReturnList(2000L, 1, this.domain,
					this.domain.getDaoimplSuffix(), daomethod));
			method.setMethodStatementList(WriteableUtil.merge(list));

			return method;
		}
	}
	public ListAll() throws Exception {
		super();
		this.dbType = "MariaDB";
		if (this.domain != null)
			this.setVerbName("ListAll" + StringUtil.capFirst(this.domain.getPlural()));
		else
			this.setVerbName("ListAll");
		this.setLabel("列出全部");
	}
	
	public ListAll(String dbType) throws Exception {
		super();
		this.dbType = dbType;
		if (this.domain != null)
			this.setVerbName("ListAll" + StringUtil.capFirst(this.domain.getPlural()));
		else
			this.setVerbName("ListAll");
		this.setLabel("列出全部");
	}

	public ListAll(Domain domain)  throws ValidateException{
		super();
		this.domain = domain;
		this.dbType = "MariaDB";
		this.denied = domain.isVerbDenied("ListAll");
		this.setVerbName("ListAll" + StringUtil.capFirst(this.domain.getPlural()));
		this.setLabel("列出全部");
		if  (domain.getLanguage().equalsIgnoreCase("english"))  this.setLabel("ListAll");
	}
	
	public ListAll(Domain domain,String dbType)  throws ValidateException{
		super();
		this.domain = domain;
		this.dbType = dbType;
		this.denied = domain.isVerbDenied("ListAll");
		this.setVerbName("ListAll" + StringUtil.capFirst(this.domain.getPlural()));
		this.setLabel("列出全部");
		if  (domain.getLanguage().equalsIgnoreCase("english"))  this.setLabel("ListAll");
	}

	@Override
	public Method generateControllerMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName(this.getVerbName());
			method.addSignature(new Signature(1,"c","*gin.Context"));

			List<Writeable> sList = new ArrayList<Writeable>();
			sList.add(new Statement(1000L,1,"var "+this.domain.getLowerFirstPlural()+" [] "+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix()+""));
			sList.add(new Statement(2000L,1,""+this.domain.getLowerFirstPlural()+" = "+this.domain.getServiceimplSuffix()+".ListAll"+this.domain.getCapFirstPlural()+"()"));
			sList.add(new Statement(3000L,1,"total := len("+this.domain.getLowerFirstPlural()+")"));
			sList.add(new Statement(4000L,1,"SendResponse(c, nil, "+this.domain.getLowerFirstPlural()+", total, true)"));
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}
	@Override
	public JavascriptBlock generateEasyUIJSButtonBlock() throws Exception {
		if (this.denied)
			return null;
		else {
			return null;
		}
	}
	@Override
	public JavascriptMethod generateEasyUIJSActionMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			return null;
		}
	}

	public Set<Field> getDeniedFields() {
		return deniedFields;
	}

	public void setDeniedFields(Set<Field> deniedFields) {
		this.deniedFields = deniedFields;
	}
}
